﻿using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.Goods;
using Coldairarrow.IBusiness.Goods;
using Coldairarrow.Entity.PersonalCenter;
using Coldairarrow.Util;
using Coldairarrow.Util.DbHelpers;
using EFCore.Sharding;
using LinqKit;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Coldairarrow.Entity.Home;
using Coldairarrow.Entity.backstage.SearchLog;

namespace Coldairarrow.Business.Goods
{
    public class BTB_HomeBusiness : BaseBusiness<BTB_Goods>, IBTB_HomeBusiness, ITransientDependency
    {
        readonly Operator _operator;
        public BTB_HomeBusiness(IDbAccessor db, Operator @operator)
            : base(db)
        {
            _operator = @operator;
        }
        public List<BTB_Goods> GetTheDataName(string where)
        {
            return GetGoodsSearch(q => q.GoodsName.Contains(where));
        }

        /// <summary>
        /// 列表分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetDataListAsync(PageInput<BTB_GoodsTypeDto> input)
        {
            #region TEST

            var bTB_GoodsTypeDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true);
            //品牌
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.Supplierid))
            {
                result = result.Where(k => k.Supplierid.Equals(bTB_GoodsTypeDto.Supplierid));
            }
            //商品名称
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsName))
            {
                result = result.Where(k => k.GoodsName.Contains(bTB_GoodsTypeDto.GoodsName));
            }
            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.Parent))
            {
                result = result.Where(k => k.RootType.Equals(bTB_GoodsTypeDto.Parent));
            }
            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsTypeId))
            {
                result = result.Where(k => k.GoodsTypeId.Equals(bTB_GoodsTypeDto.GoodsTypeId));
            }
            //价格
            if (bTB_GoodsTypeDto.Startprice >= 0 && bTB_GoodsTypeDto.Endprice > 0)
            {
                result = result.Where(k => k.GoodsPrices > bTB_GoodsTypeDto.Startprice && k.GoodsPrices < bTB_GoodsTypeDto.Endprice);
            }
            //是否热销
            if (bTB_GoodsTypeDto.IsHot.HasValue)
            {
                result = result.Where(k => k.IsHot == bTB_GoodsTypeDto.IsHot);
            }

            //是否特惠
            if (bTB_GoodsTypeDto.Preferential.HasValue)
            {
                result = result.Where(k => k.Preferential == bTB_GoodsTypeDto.Preferential);
            }

            //是否今日爆款
            if (bTB_GoodsTypeDto.IsSpecial.HasValue)
            {
                result = result.Where(k => k.SpecialType == bTB_GoodsTypeDto.IsSpecial);
            }

            var where = LinqHelper.True<BTB_Goods>();
            //范围 --只是提示这里  价格范围可以用以下方法组成查询条件放到第二表的where（where）
            //if ((bTB_GoodsTypeDto.startPrice!=null))
            //{
            //    var newWhere = DynamicExpressionParser.ParseLambda<BTB_Goods, bool>(
            //              ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
            //    where = where.And(newWhere);
            //}

            int count = result.Count();
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,
                MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                Inventory = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Inventory,
                GoodsSpecificationsItemID = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().GoodsSpecificationsItemID,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Price,
                IsHot = s.IsHot,
                SaleCount = s.SaleCount,
                warning = s.warning,
                CreateTime = s.CreateTime,
                Stock = s.Stock,
                SpecificationsItem = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(k => k.IsSale == true && k.Price >= bTB_GoodsTypeDto.Startprice && k.Price <= bTB_GoodsTypeDto.Endprice)
            }).OrderBy(input.SortField, input.SortType).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();
            
            return new PageResult<BTB_GoodsDto> { Data = q, Total = count };
            #endregion
        }


        /// <summary>
        /// 列表分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<TheGoodsDTO>> GetGSDataListAsync(PageInput<GetDataSearchDTO> input)
        {
            #region TEST

            var bTB_GoodsTypeDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true);

            var where = LinqHelper.True<TheGoodsDTO>();

            //商品名称
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsName))
            {
                result = result.Where(k => k.GoodsName.Contains(bTB_GoodsTypeDto.GoodsName));

                //插入记录
                BS_SearchLog model = new BS_SearchLog();
                model.Id = IdHelper.GetId();
                model.CreateTime = DateTime.Now;
                model.CreatorId = _operator?.UserId;
                model.Deleted = false;
                model.SearchWord = bTB_GoodsTypeDto.GoodsName;
                model.UserId = _operator?.UserId;
                model.Time = DateTime.Now;

                Db.Insert(model);

                //获取查询历史
                List<BS_SearchWord> asList = new List<BS_SearchWord>();
                var sList = Db.GetIQueryable<BS_SearchWord>().Where(x => bTB_GoodsTypeDto.GoodsName.Contains(x.Word)).ToList();

                var eCount = Db.GetIQueryable<BS_SearchWord>().Where(x => bTB_GoodsTypeDto.GoodsName.Equals(x.Word)).Count();

                foreach (var item in sList)
                {
                    BS_SearchWord smodel = item;
                    smodel.Times += 1;
                    asList.Add(smodel);
                }

                if (asList.Count > 0)
                {
                    Db.Update(asList);
                }

                if (eCount == 0)
                {
                    BS_SearchWord bsModel = new BS_SearchWord();
                    bsModel.Id = IdHelper.GetId();
                    bsModel.CreateTime = DateTime.Now;
                    bsModel.CreatorId = _operator?.UserId;
                    bsModel.Deleted = false;
                    bsModel.Word = bTB_GoodsTypeDto.GoodsName;
                    bsModel.Times = 1;
                    Db.Insert(bsModel);
                }
            }

            //价格
            if (bTB_GoodsTypeDto.Startprice.HasValue && bTB_GoodsTypeDto.Endprice.HasValue)
            {
                result = result.Where(k => k.GoodsPrices > bTB_GoodsTypeDto.Startprice && k.GoodsPrices < bTB_GoodsTypeDto.Endprice);
            }


            //是否热销
            if (bTB_GoodsTypeDto.IsHot.HasValue)
            {
                result = result.Where(k => k.IsHot == bTB_GoodsTypeDto.IsHot);
            }

            //是否特惠
            if (bTB_GoodsTypeDto.Preferential.HasValue)
            {
                result = result.Where(k => k.Preferential == bTB_GoodsTypeDto.Preferential);
            }

            //是否今日爆款
            if (bTB_GoodsTypeDto.IsSpecial.HasValue)
            {
                result = result.Where(k => k.SpecialType == bTB_GoodsTypeDto.IsSpecial);
            }

            //是否今日爆款
            if (!bTB_GoodsTypeDto.RootTypeTwo.IsNullOrEmpty()) 
            {
                result = result.Where(k => k.RootTypeTwo == bTB_GoodsTypeDto.RootTypeTwo);
            }

            if (!bTB_GoodsTypeDto.IsPointGood.HasValue)
            {
                result = result.Where(k => k.IsPointGoods == bTB_GoodsTypeDto.IsPointGood);
            }
            else
            {
                result = result.Where(k => k.IsPointGoods == false);
            }

            if (bTB_GoodsTypeDto.IsPointGood.HasValue && bTB_GoodsTypeDto.IsPointGood == true)
            {
                var q = await result.Select(s => new TheGoodsDTO
                {
                    ID = s.ID,
                    GoodsName = s.GoodsName,
                    CreateTime =s.CreateTime,
                    GoodsDescribe = s.GoodsDescribe,
                    MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().MarkingPrice,
                    RootType = s.RootType,
                    RootTypeTwo = s.RootTypeTwo,
                    GoodsPic = s.GoodsPic,
                    GoodsPrices = 99999,
                    PointPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().PointPrice,
                    SaleCount = s.SaleCount,
                    IsHot = s.IsHot,
                    Preferential = s.Preferential,
                    SpecialType = s.SpecialType,
                    Stock = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().stock.HasValue?0:(int)Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().stock
                }).OrderBy(input.SortField, input.SortType).ToListAsync();

                int count = q.Count;

                var dList = q.Skip((input.PageIndex - 1) * input.PageRows)
                    .Take(input.PageRows)
                    .ToList();

                return new PageResult<TheGoodsDTO> { Data = dList, Total = count };
            }
            else
            {
               


                var q = await result.Select(s => new TheGoodsDTO
                {
                    ID = s.ID,
                    GoodsName = s.GoodsName,
                    CreateTime = s.CreateTime,
                    GoodsDescribe = s.GoodsDescribe,
                    MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.Price).FirstOrDefault().MarkingPrice,
                    RootType = s.RootType,
                    RootTypeTwo = s.RootTypeTwo,
                    GoodsPic = s.GoodsPic,
                    GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.Price).FirstOrDefault().Price,
                    PointPrices = 99999,
                    SaleCount = s.SaleCount,
                    IsHot = s.IsHot,
                    Preferential = s.Preferential,
                    SpecialType = s.SpecialType,
                    Stock = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().stock.HasValue ? 0 : (int)Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).OrderBy(x => x.PointPrice).FirstOrDefault().stock
                }).OrderBy(input.SortField, input.SortType).ToListAsync();

                int count = q.Count;

                var dList = q.Skip((input.PageIndex - 1) * input.PageRows)
                    .Take(input.PageRows)
                    .ToList();

                return new PageResult<TheGoodsDTO> { Data = dList, Total = count };
            }
           
            #endregion
        }

        /// <summary>
        /// 列表分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetSVDataListAsync(PageInput<BTB_GoodsTypeDto> input)
        {
            #region TEST

            var bTB_GoodsTypeDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true);
            //品牌
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.Supplierid))
            {
                result = result.Where(k => k.Supplierid.Equals(bTB_GoodsTypeDto.Supplierid));
            }
            //商品名称
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsName))
            {
                result = result.Where(k => k.GoodsName.Contains(bTB_GoodsTypeDto.GoodsName));
            }
            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.Parent))
            {
                result = result.Where(k => k.RootType.Equals(bTB_GoodsTypeDto.Parent));
            }
            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsTypeId))
            {
                result = result.Where(k => k.GoodsTypeId.Equals(bTB_GoodsTypeDto.GoodsTypeId));
            }
            //价格
            if (bTB_GoodsTypeDto.Startprice >= 0 && bTB_GoodsTypeDto.Endprice > 0)
            {
                result = result.Where(k => k.GoodsPrices > bTB_GoodsTypeDto.Startprice && k.GoodsPrices < bTB_GoodsTypeDto.Endprice);
            }
            //是否热销
            if (bTB_GoodsTypeDto.IsHot.HasValue)
            {
                result = result.Where(k => k.IsHot == bTB_GoodsTypeDto.IsHot);
            }

            //是否特惠
            if (bTB_GoodsTypeDto.Preferential.HasValue)
            {
                result = result.Where(k => k.Preferential == bTB_GoodsTypeDto.Preferential);
            }

            //是否今日爆款
            if (bTB_GoodsTypeDto.IsSpecial.HasValue)
            {
                result = result.Where(k => k.SpecialType == bTB_GoodsTypeDto.IsSpecial);
            }

            var where = LinqHelper.True<BTB_Goods>();
            //范围 --只是提示这里  价格范围可以用以下方法组成查询条件放到第二表的where（where）
            //if ((bTB_GoodsTypeDto.startPrice!=null))
            //{
            //    var newWhere = DynamicExpressionParser.ParseLambda<BTB_Goods, bool>(
            //              ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
            //    where = where.And(newWhere);
            //}

            int count = result.Count();
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,
                MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                Inventory = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Inventory,
                GoodsSpecificationsItemID = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().GoodsSpecificationsItemID,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Price,
                IsHot = s.IsHot,
                SaleCount = s.SaleCount,
                warning = s.warning,
                CreateTime = s.CreateTime,
                Stock = s.Stock,
                SpecificationsItem = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(k => k.IsSale == true && k.Price >= bTB_GoodsTypeDto.Startprice && k.Price <= bTB_GoodsTypeDto.Endprice)
            }).OrderBy(input.SortField, input.SortType).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            return new PageResult<BTB_GoodsDto> { Data = q, Total = count };
            #endregion
        }

        /// <summary>
        /// 特惠列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<BTB_GoodsDto>> GetPreferentialListAsync()
        {
            #region TEST


            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true && k.Preferential == true);
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,
                MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Price,
                IsHot = s.IsHot,
                warning = s.warning,
                Stock = s.Stock,
            }).ToListAsync();
            return q;
            #endregion
        }
        /// <summary>
        /// 列表分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetDataListAsync2(PageInput<BTB_GoodsTypeDto> input)
        {
            #region TEST

            var bTB_GoodsTypeDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true);
            //品牌
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.Supplierid))
            {
                result = result.Where(k => k.Supplierid.Equals(bTB_GoodsTypeDto.Supplierid));
            }
            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.id))
            {
                result = result.Where(k => k.GoodsTypeId.Equals(bTB_GoodsTypeDto.id));
            }
            var where = LinqHelper.True<BTB_Goods>();

            int count = result.Count();
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                CreatorId = s.CreatorId,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,
                MarkingPrice = s.MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID).FirstOrDefault().Price,
                IsHot = s.IsHot,
                Details = s.Details,
                warning = s.warning,
                Stock = s.Stock,
                CreateTime = s.CreateTime,
                Editor = s.Editor,
                EditTime = s.EditTime,
                Deleted = s.Deleted,
                IsSale = s.IsSale,
                SpecificationsItem = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(k => k.IsSale == true && k.Price >= bTB_GoodsTypeDto.Startprice && k.Price <= bTB_GoodsTypeDto.Endprice)
            }).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            return new PageResult<BTB_GoodsDto> { Data = q, Total = count };

            #endregion
        }
        /// <summary>
        /// 商品管理列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetGoodsList(PageInput<BTB_GoodsDto> input)
        {
            var bTB_GoodsTypeDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>();
            //品牌
            if (!string.IsNullOrEmpty(bTB_GoodsTypeDto.GoodsName))
            {
                result = result.Where(k => k.GoodsName.Equals(bTB_GoodsTypeDto.GoodsName));
            }
            var where = LinqHelper.True<BTB_Goods>();

            int count = result.Count();
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                CreatorId = s.CreatorId,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,//是否特惠
                MarkingPrice = s.MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(p => p.GoodsID == s.ID && p.IsSale == true).FirstOrDefault().Price,
                IsHot = s.IsHot,
                Details = s.Details,
                warning = s.warning,
                Stock = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(p => p.GoodsID == s.ID).Sum(g => g.Inventory),
                _CreateTime = s.CreateTime,
                Editor = s.Editor,
                EditTime = s.EditTime,
                Deleted = s.Deleted,
                IsSale = s.IsSale,
                GoodsPicS = Db.GetIQueryable<BTB_GoodsPic>(true).Where(p => p.GoodsID == s.ID),
                Parametes = Db.GetIQueryable<BTB_GoodsParamete>(true).Where(p => p.Goodsid == s.ID)
            }).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            return new PageResult<BTB_GoodsDto> { Data = q, Total = count };
        }

        public async Task<List<BTB_GoodsTypeDto>> GetAll(int Top)
        {
            try
            {
                var res = (from p in Db.GetIQueryable<BTB_GoodsType>().Where(p => p.Parent.Equals("0"))
                           select new BTB_GoodsTypeDto
                           {
                                id = p.id,
                                Sort = p.Sort,
                                TypeName = p.TypeName,
                                BTB_NewProduct =from h in Db.GetIQueryable<BTB_NewProducts>(false).Where(h => h.GoodsTypeid == p.id) select h,
                              
                               GoodsTypeDto = (from s in Db.GetIQueryable<BTB_GoodsType>(false).Where(s => s.Parent.Equals(p.id))
                                               select new BTB_GoodsTypeDto
                                               {
                                                   id = s.id,
                                                   TypeName = s.TypeName,
                                                   Parent = s.Parent,
                                                   Sort = s.Sort,
                                                   BTB_GoodsDTO = from k in Db.GetIQueryable<BTB_Goods>(true).Where(k => k.RootTypeTwo.Equals(s.id) && k.IsSale == true).Take(Top)
                                                                  orderby k.SaleCount descending
                                                                  join t in Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(t => t.IsSale == true) on k.ID equals t.GoodsID
                                                                  select new BTB_Goods
                                                                  {
                                                                      ID = k.ID,
                                                                      GoodsName = k.GoodsName,
                                                                      GoodsDescribe = k.GoodsDescribe,
                                                                      GoodsPic = k.GoodsPic,
                                                                      Details = k.Details,
                                                                      GoodsPrices = t.Price,
                                                                      SaleCount = t.Inventory
                                                                  }
                                               }).OrderByDescending(x => x.Sort).ThenByDescending(x => x.id)
                           }).OrderByDescending(x => x.Sort).ThenByDescending(x => x.id).ToListAsync();
                return await res;
            }
            catch (Exception E)
            {

                throw;
            }
          
        }

        /// <summary>
        /// 首页广告
        /// </summary>
        /// <param name="id">商品类型id</param>
        /// <returns></returns>
        public async Task<List<BTB_NewProducts>> GetNewProducts(string id)
        {
            return await Db.GetIQueryable<BTB_NewProducts>(true).Where(q => q.GoodsTypeid == id).ToListAsync();
        }
        /// <summary>
        /// 首页供货商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<BTB_Supplier>> GetSupplier(string id)
        {
            var aa = (Db.GetIQueryable<BTB_Supplier>()
                  .Select(
                  a => new BTB_Supplier
                  {
                      id = a.id,
                      CreatorId = a.CreatorId,
                      Name = a.Name,
                      Address = a.Address,
                      SupplierLogo = a.SupplierLogo,
                      Phone = a.Phone,
                      PhoneName = a.PhoneName,
                      CreateTime = a.CreateTime,
                      Editor = a.Editor,
                      EditTime = a.EditTime,
                      Deleted = a.Deleted,
                      Accuracy = a.Accuracy,
                      Latitude = a.Latitude,
                      counts = Db.GetIQueryable<BTB_Goods>(true).Where(q => q.Supplierid == a.id && q.RootType == id).Sum(q => q.SaleCount)
                  }).OrderBy("counts", "DESC").Take(5)).ToListAsync();
            return await aa;
        }


        /// <summary>
        /// 获取首页商品信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetIndexGoods(GetIndexSearch input)
        {
            PageResult<BTB_GoodsDto> dData = new PageResult<BTB_GoodsDto>();
            int scount = input.PageRow * (input.PageIndex - 1);
            var goods = await Db.GetIQueryable<BTB_Goods>().Where(i => i.SpecialType == input.SType && i.IsSale == true)
                 .Select(
                 a => new BTB_GoodsDto
                 {
                     ID = a.ID,
                     GoodsName = a.GoodsName,
                     GoodsDescribe = a.GoodsDescribe,
                     MarkingPrice = a.MarkingPrice,
                     GoodsPic = a.GoodsPic,
                     GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(q => q.GoodsID == a.ID && q.IsSale == true).FirstOrDefault().Price,
                 }).OrderBy("ID", "DESC").ToListAsync();

            int total = goods.Count;
            var data = goods.Skip(scount).Take(input.PageRow).ToList();

            dData.Total = total;
            dData.Data = data;


            return dData;
        }

        /// <summary>
        /// 获取首页商品列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetIndexGoosList(PageInput<GetIndexGoosList> input)
        {
            var search = input.Search;
            var goods = Db.GetIQueryable<BTB_Goods>()
                .Where(i => i.IsSale == true)
                .WhereIf(search.IsHot.HasValue,x => x.IsHot == search.IsHot)
                .WhereIf(search.Preferential.HasValue, x => x.Preferential == search.Preferential)
                .WhereIf(search.SpecialType.HasValue, x => x.SpecialType == search.SpecialType)
                .WhereIf(search.IsPointGoods.HasValue, x => x.IsPointGoods == search.IsPointGoods)
                .Select(
                 a => new BTB_GoodsDto
                 {
                     ID = a.ID,
                     GoodsName = a.GoodsName,
                     GoodsDescribe = a.GoodsDescribe,
                     MarkingPrice = a.MarkingPrice,
                     IsPointGoods = a.IsPointGoods,
                     PointPrice = a.PointPrice,
                     GoodsPic = a.GoodsPic,
                     GoodsPrices = a.GoodsPrices
                 }).OrderBy("ID", "DESC");

            var data = await goods.GetPageResultAsync(input);

            return data;
        }

        public async Task<List<BTB_GoodsDto>> GetIsHont(int Top)
        {
            var goods = Db.GetIQueryable<BTB_Goods>()
                .Where(i => i.IsHot == true && i.IsSale == true)
                .Where(a => a.IsPointGoods == false)
                 .Select(
                 a => new BTB_GoodsDto
                 {
                     ID = a.ID,
                     GoodsName = a.GoodsName,
                     GoodsDescribe = a.GoodsDescribe,
                     MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(q => q.GoodsID == a.ID && q.IsSale == true).OrderBy(x => x.Price).FirstOrDefault().MarkingPrice,
                     GoodsPic = a.GoodsPic,
                     GoodsPrices = a.GoodsPrices
                 }).OrderBy("ID", "DESC").Take(Top).ToListAsync();
            return await goods;
        }
        public async Task<List<BTB_GoodsDto>> GetPreferential(int Top)
        {
            var goods = Db.GetIQueryable<BTB_Goods>()
                .Where(i => i.IsSale == true && i.Preferential == true)
                .Where(a => a.IsPointGoods == false)
                .Select(
                 a => new BTB_GoodsDto
                 {
                     ID = a.ID,
                     GoodsDescribe = a.GoodsDescribe,
                     GoodsName = a.GoodsName,
                     MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(q => q.GoodsID == a.ID && q.IsSale == true).OrderBy(x =>x.Price).FirstOrDefault().MarkingPrice,
                     GoodsPic = a.GoodsPic,
                     GoodsPrices = a.GoodsPrices
                 }).OrderBy("ID", "DESC").Take(Top).ToListAsync();
            return await goods;
        }

        public List<GoodsSpecificationsDTO> Specifications(string id)
        {
            var str = "SELECT DISTINCT specification, STUFF((SELECT ',' + value FROM BTB_GoodsSpecifications WHERE Goodsid='" + id + "'  and specification = T.specification FOR XML PATH('') ), 1, 1, '') AS value FROM BTB_GoodsSpecifications AS T where  Goodsid='" + id + "'";
            var data = DbHelperSQL.QueryForList<GoodsSpecificationsDTO>(str).OrderBy(x => x.specification).ThenBy(x => x.value).ToList();
            if (data.Count > 0)
            {
                return data;
            }
            else
            {
                throw new BusException("该商品没有规格", errorCode: -1);
            }
        }
        public async Task<List<BTB_GoodsDto>> GetGoods(string Goodsname)
        {
            return await GetIQueryable().Where(q => q.GoodsName.Contains(Goodsname)).Select(a => new BTB_GoodsDto
            {
                ID = a.ID,
                GoodsName = a.GoodsName,
                SpecificationsItem = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == a.ID)
            }).ToListAsync();
        }
        /// <summary>
        /// 小程序首页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<BTB_GoodsDto>> GetWeChatListAsync(PageInput<GoodsDTO> input)
        {
            #region TEST

            var bTB_GoodsDto = input.Search;

            var result = Db.GetIQueryable<BTB_Goods>().Where(k => k.IsSale == true);

            //类型
            if (!string.IsNullOrEmpty(bTB_GoodsDto.Typeid))
            {
                result = result.Where(k => k.RootTypeTwo.Equals(bTB_GoodsDto.Typeid));
            }

            var where = LinqHelper.True<BTB_Goods>();

            int count = result.Count();
            var q = await result.Select(s => new BTB_GoodsDto
            {
                ID = s.ID,
                GoodsName = s.GoodsName,
                GoodsTypeId = Db.GetIQueryable<BTB_GoodsType>(true).Where(z => z.id == s.GoodsTypeId).FirstOrDefault().TypeName,
                Preferential = s.Preferential,
                MarkingPrice = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().MarkingPrice,
                GoodsDescribe = s.GoodsDescribe,
                GoodsPic = s.GoodsPic,
                Specifications = s.Specifications,
                GoodsPrices = Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(z => z.GoodsID == s.ID && z.IsSale == true).FirstOrDefault().Price,
                IsHot = s.IsHot,
                warning = s.warning,
                Stock = s.Stock,
            }).Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync();

            return new PageResult<BTB_GoodsDto> { Data = q, Total = count };
            #endregion
        }
        //SaleCount
        public async Task<List<BTB_GoodsTypeDto>> Get()
        {
            var res = (from p in Db.GetIQueryable<BTB_GoodsType>().Where(p => p.Parent.Equals("0"))
                       select new BTB_GoodsTypeDto
                       {
                           id = p.id,
                           TypeName = p.TypeName,
                           BTB_GoodsDTO = from k in Db.GetIQueryable<BTB_Goods>(true).Where(k => k.RootType.Equals(p.id) && k.IsSale == true).Take(5)
                                          orderby k.SaleCount descending
                                          join t in Db.GetIQueryable<BTB_GoodsSpecificationsItem>(true).Where(t => t.IsSale == true) on k.ID equals t.GoodsID
                                          select new BTB_Goods
                                          {
                                              ID = k.ID,
                                              GoodsName = k.GoodsName,
                                              GoodsDescribe = k.GoodsDescribe,
                                              GoodsPic = k.GoodsPic,
                                              Details = k.Details,
                                              GoodsPrices = t.Price,
                                              SaleCount = t.Inventory
                                          }
                       }).ToListAsync();
            return await res;
    }

}

}